import { applyMiddleware, compose, createStore } from 'redux';

import { routerMiddleware } from 'react-router-redux';
import createHistory from 'history/createBrowserHistory';

//https://github.com/gaearon/redux-thunk
import thunkMiddleware from 'redux-thunk';

import rootReducer from './reducers';
import { reducers } from '../reducers/';

const globalStore = (initialState: any = {}) => {
  const { hot } = module as any;
  const history = createHistory();
  // Build the middleware for intercepting and dispatching navigation actions
  const historyMiddleware = routerMiddleware(history);
  const middlewares = [thunkMiddleware, historyMiddleware];

  const store: any = createStore(
    rootReducer(reducers),
    initialState,
    compose(
      applyMiddleware(...middlewares)
    )
  );

  // 支持webpack reducer 热替换
  if (hot) {
    hot.accept('./reducers', () => {
      const reducers = require('./reducers').default;
      store.replaceReducer(reducers(store.asyncReducers));
    });
  }

  return store;
};

export default globalStore;
